package database

func FindByUserName(userName string) (*User, error) {
	user := &User{}
	err := db.First(user, "user_name = ?", userName).Scan(user).Error
	return user, err
}

func FindUserById(userId int64) (*User, error) {
	user := &User{}
	err := db.First(user, "id = ?", userId).Scan(user).Error
	return user, err
}

func UpdateUser(user *User) error {
	err := db.Save(user).Error
	return err
}

// 根据给定的group表的ID查询所有用户
func ListUsersByGroupID(groupID int64) ([]User, error) {
	var users []User
	var userGroups []UserGroup

	// 查询user_group表，找到所有与给定group表ID相关联的记录
	if err := db.Where("group_id = ?", groupID).Find(&userGroups).Error; err != nil {
		return nil, err
	}

	// 提取user_group表中的userID字段
	var userIDs []int64
	for _, userGroup := range userGroups {
		userIDs = append(userIDs, userGroup.UserID)
	}

	// 根据提取到的userID，在user表中查询对应的用户记录
	if err := db.Where("id IN (?)", userIDs).Find(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}
